<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/utils/api'
import Toast from '@/components/Toast.vue'
import { showToast } from '@/utils/toast'

const router = useRouter()
const username = ref('') // 用户名
const password = ref('') // 密码
const confirmPassword = ref('') // 确认密码
const phone = ref('') // 手机号
const verifyCode = ref('') // 验证码
const countdown = ref(0) // 倒计时秒数

// 修改错误提示的方法
const showError = (message) => {
  showToast(message, 'error')
}

// 修改成功提示的方法
const showSuccess = (message) => {
  showToast(message, 'success')
}

// 获取验证码
const getVerifyCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showError('请输入有效的11位手机号码')
    return
  }

  // 生成验证码
  try {
    const response = await api.post('/api/verify_code', {
      phone: phone.value,
    })
    if (response.data.code === 0) {
      showToast(response.data.message, 'success')
    }
    else{
        showToast(response.data.message, 'error')
      }
  } catch (error) {
    showToast(error.message, 'error')
  }

  // 开始倒计时
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理注册
const handleRegister = async () => {
  if (!username.value || !password.value || !confirmPassword.value || !phone.value || !verifyCode.value) {
    showError('所有内容必须填写')
    return
  }

  // 验证用户名格式（4-16位字母数字）
  if (!/^[a-zA-Z0-9]{4,16}$/.test(username.value)) {
    showError('用户名必须是4-16位字母或数字的组合')
    return
  }

  // 验证密码格式（6-16位字母数字）
  if (!/^[a-zA-Z0-9]{6,16}$/.test(password.value)) {
    showError('密码必须是6-16位字母或数字的组合')
    return
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showError('请输入有效的11位手机号码')
    return
  }

  // 验证验证码是否为4位数字
  if (!/^\d{4}$/.test(verifyCode.value)) {
    showError('验证码必须是4位数字')
    return
  }

  // 验证密码一致性
  if (password.value !== confirmPassword.value) {
    showError('两次输入的密码不一致')
    return
  }

  try {
    const response = await api.post('/api/register', {
      username: username.value,
      password: password.value,
      phone: phone.value.toString(),
      verifyCode: verifyCode.value.toString()
    })
    
    if (response.data.code === 0) {
      showSuccess('注册成功！正在跳转到登录页...')
      setTimeout(() => {
        router.push('/')
      }, 2000)
    } else {
      showError(response.data.message)
    }
  } catch (error) {
    showError(error.message)
  }
}
</script>

<template>
  <div class="wrapper">
    <Toast />
    <div class="register-container">
      <div class="register-box">
        <h2>用户注册</h2>
        <div class="register-form">
          <div class="form-item">
            <input 
              type="text" 
              v-model="username" 
              placeholder="用户名（4-16位字母或数字）" 
            >
          </div>
          <div class="form-item">
            <input 
              type="password" 
              v-model="password" 
              placeholder="密码（6-16位字母或数字）" 
            >
          </div>
          <div class="form-item">
            <input 
              type="password" 
              v-model="confirmPassword" 
              placeholder="确认密码" 
            >
          </div>
          <div class="form-item">
            <input 
              type="text" 
              v-model="phone" 
              placeholder="手机号（11位）" 
              maxlength="11"
            >
          </div>
          <div class="form-item phone-verify">
            <input 
              type="text" 
              v-model="verifyCode" 
              placeholder="请输入验证码" 
              maxlength="6"
            >
            <button 
              class="verify-code-btn" 
              @click="getVerifyCode" 
              :disabled="countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </button>
          </div>
          <button @click="handleRegister">注 册</button>
          <div class="login-link">
            <router-link to="/">已有账号？ 返回登录</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-box {
  background: rgba(255, 255, 255, 0.95);
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  position: relative;
}

input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s;
}

input:focus {
  border-color: #667eea;
  outline: none;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

button {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

button:hover {
  background: #5a6fd6;
  transform: translateY(-1px);
}

button:active {
  transform: translateY(0);
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  text-align: center;
}

.login-link {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  font-size: 16px;
  gap: 4px;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-link a:hover {
  color: #5a6fd6;
  text-decoration: none;
  opacity: 0.8;
}

.phone-verify {
  display: flex;
  gap: 10px;
}

.verify-code-btn {
  width: auto;
  white-space: nowrap;
  padding: 0 15px;
  font-size: 14px;
  background: #667eea;
}

.verify-code-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.phone-verify input {
  flex: 1;
}
</style> 